#include "app_uart.h"

static void parse_action(void);

/**
 * @函数描述: uart串口相关设备控制初始化
 * @return {*}
 */
void app_uart_init(void)
{
    uart1_init(115200); /* uart1串口初始化 */
}

/**
 * @函数描述: 循环检测串口接收到的指令
 * @return {*}
 */
void app_uart_run(void)
{
    if (uart1_get_ok) /* 接收到上位机指令 */
    {
        uart1_get_ok = 0;
        uart1_mode = 0;
        parse_action();/* 解析指令 */
    }
}

/* 处理 #000P1500T1000! 类似的字符串 */
static void parse_action(void)
{
    uint16_t time, i = 0;
    u16 index;
    float pwm;

    printf("parse_action = %s\r\n", uart_receive_buf);

    while (uart_receive_buf[i])
    {
        if (uart_receive_buf[i] == '#') /* 指令的开始，先找出下标 */
        {
            index = 0;
            i++;
            while (uart_receive_buf[i] && uart_receive_buf[i] != 'P')
            {
                index = index * 10 + uart_receive_buf[i] - '0';
                i++;
            }
        }
        else if (uart_receive_buf[i] == 'P') /* 检测到P，开始计算舵机执行目标 */
        {
            pwm = 0;
            i++;
            while (uart_receive_buf[i] && uart_receive_buf[i] != 'T')
            {
                pwm = pwm * 10 + uart_receive_buf[i] - '0';
                i++;
            }
        }
        else if (uart_receive_buf[i] == 'T') /* 检测到T ，舵机执行时间 */
        {
            time = 0;
            i++;
            while (uart_receive_buf[i] && uart_receive_buf[i] != '!')
            {
                time = time * 10 + uart_receive_buf[i] - '0';
                i++;
            }

            servo_data_set(index, pwm, time);/* 设置舵机控制参数函数 */

            if (index == 255)
            {
                for (index = 0; index < SERVO_NUM; index++)
                {
                    servo_data_set(index, pwm, time);/* 设置舵机控制参数函数 */
                }
            }
        }
        else
        {
            i++;
        }
    }
}
